package redis

import (
	"encoding/json"
	"github.com/go-redis/redis/v7"
	"grab-train-ticket/grab-ticket4go/utils/resp"
	"time"
)

var rdb *redis.Client

func init() {
	rdb = redis.NewClient(&redis.Options{
		Addr:         "127.0.0.1:6379", //TODO 改成读配置文件
		Password:     "redisCh",
		DialTimeout:  10 * time.Second,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
		PoolSize:     10,
		PoolTimeout:  30 * time.Second,
	})
}

func Get(key string) (val string) {
	val, _ = rdb.Get(key).Result()
	return val
}

func Del(key string) {
	rdb.Del(key)
}

func Set(key string, val interface{}, expiration time.Duration) {
	var err error
	switch val.(type) { //类型switch判断
	case string: //如果值是字符串，直接set到redis
		err = rdb.Set(key, val, expiration).Err()
		if err != nil {
			panic(resp.Common_redis) //set异常
		}
	default: //如果值不是字符串则转为json后再set到redis
		valJson, err := json.Marshal(val)
		if err != nil {
			panic(resp.Common_redis) //对象转json异常
		}
		err = rdb.Set(key, valJson, expiration).Err()
		if err != nil {
			panic(resp.Common_redis) //set异常
		}
	}
}
